#include <stdio.h>
#include <stdlib.h>
#include "lockcond.h"

void lock_init(struct lock* l){
	l = (lock*)malloc(sizeof(lock));
	l->mutex = 1;
	l->next = 2;
	seminit(l->mutex, 1);
	seminit(l->next, 0);
	l->nextCount = 0;
}

/* void lock_acquire(struct lock* l){
	semdown(l->mutex);
} */

void lock_acquire(struct lock*l){
	if(l->nextCount > 0)
		semup(l->next);
	else
		semup(l->mutex);
} 

void cond_init(struct cond *cnd, struct lock *l){
	cnd = (cnd*)malloc(sizeof(cnd));
	lock_init(cnd->l);
	cnd->condSem = 0;
	seminit(cnd->condSem, 0);
	cond->semCount = 0;
}

void cond_wait(struct cond *cnd){
	cnd->semCount = cnd->semCount + 1;
	if(cnd->l->nextCount > 0)
		semup(cnd->l->next);
	else
		semup(cnd->l->mutex);
	semdown(cnd->condSem);
	cnd->semCount -= 1;

}

void cond_signal (struct cond *cnd){
	if(cnd->semCount > 0){
		cnd->l->nextCount += 1;
		semup(cnd->condSem);
		semdown(cnd->l->next);
		cnd->l->nextCount -= 1;
	}
}